<template>
  <div>
    <FixedOperation>
      <el-row>
        <el-col :span="10" :offset="14" class="flex justify-end">
          <el-button type="primary" plain @click="save"> 保存</el-button>
          <!-- <el-button type="primary" plain v-if="isAdd" @click="release">
            发布</el-button
          > -->
          <!-- <el-button type="primary" plain v-if="!isAdd" @click="agree">
            同意</el-button
          >
          <el-button type="primary" plain v-if="!isAdd" @click="modification">
            退回修改</el-button
          >
          <el-button type="primary" plain v-if="!isAdd" @click="Rejection">
            驳回申请</el-button
          >
          <el-button type="primary" plain v-if="!isAdd" @click="process">
            查看流程</el-button
          > -->
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="templatePage app-container">
      <el-form id="temForm" :rules="rules" ref="templateFrom" :model="form">
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="合同模板标题："
              style="width: 100%"
              label-width="180px"
              prop="title"
            >
              <el-input
                v-model="form.title"
                placeholder="请输入合同模板标题"
                style="width: 60%"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="合同模板类型："
              style="width: 100%"
              label-width="180px"
              prop="type"
            >
              <el-select
                v-model="form.type"
                placeholder="请输入合同模板类型"
                clearable
              >
                <el-option
                  v-for="item in contract_template_type"
                  :key="item.label + item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <el-form-item
              label="合同模板状态："
              style="width: 100%"
              label-width="180px"
              prop="status"
            >
              <el-radio-group v-model="form.status">
                <el-radio label="1" size="large">在用</el-radio>
                <el-radio label="2" size="large">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4" style="flex-wrap: wrap">
            <el-form-item
              label="上传合同模板："
              style="width: 100%"
              label-width="180px"
              prop="file"
            >
              <el-upload
                v-model="form.upload"
                class="upload-demo"
                action="#"
                accept=".rar, .zip, .doc, .docx, .pdf"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadEvent"
                :show-file-list="false"
              >
                <el-button type="primary">上传合同模板</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                  </div>
                </template>
              </el-upload>
              <div class="text-14px" style="width: 100%">
                <div v-for="(item, index) in fileList" :key="item.fileId">
                  <a :href="item.url">{{ item.fileName }}</a>
                  <el-button text plain @click="delFileName(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 100%">
          <el-col :span="18" :offset="4">
            <!-- <div class="label">
              <span class="tip">*</span>
              <span>可见范围：</span>
            </div> -->
            <el-form-item
              label="公开状态："
              style="width: 100%"
              label-width="180px"
              prop="viewRange"
            >
              <el-radio-group v-model="form.viewRange" size="large">
                <el-radio-button
                  v-for="item in open_state"
                  :key="item.label"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
              <!-- <el-input
                v-if="form.viewRange === '3'"
                v-model="viewPersons"
                class="ml-15px"
                style="width: 300px"
                @focus="changePerson"
              ></el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18" :offset="4">
            <!-- <div class="label"><span>模板说明：</span></div> -->
            <el-form-item
              label="模板说明："
              label-width="180px"
              style="width: 100%"
            >
              <el-input
                type="textarea"
                v-model="form.telExplain"
                placeholder="输入模板说明"
                :rows="5"
                maxlength="100"
                show-word-limit
            /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <SelectDialog
        :dialogParam="dialogParam"
        @ok="selectFromValue"
        @close="closeDialog"
      />
    </div>
  </div>
</template>

<script setup name="addTemplate">
import FixedOperation from '@/components/FixedOperation'
import SelectDialog from '@/components/SelectDialog/copy.vue'
import {
  reactive,
  getCurrentInstance,
  toRefs,
  watchEffect,
  watch,
  ref
} from 'vue'
import { useRouter } from 'vue-router'
import {
  contractSave,
  contractUpdate,
  contractdetails,
  uploadFile,
  delFile
} from '@/api/salesManage/contractManage'
import useCommonStore from '@/store/modules/common'
import {
  templace_status,
  contract_template_type,
  open_state
} from '@/hooks/dict/contract.js'
import useTagsViewStore from '@/store/modules/tagsView'
const { proxy } = getCurrentInstance()
const router = useRouter()
const commonStore = useCommonStore()
const data = reactive({
  form: {
    title: '',
    type: '',
    status: '1',
    viewRange: '0',
    viewPersons: '',
    upload: null,
    fileNames: [],
    telExplain: '',
    defaultCheckedKeys: [],
    ctId: ''
  },
  dialogParam: {},
  fileList: [],
  personList: [],
  rules: {
    title: [{ required: true, message: '请输入合同标题', trigger: 'blur' }],
    status: [{ required: true }],
    type: [{ required: true, message: '请选择合同模板类型', trigger: 'blur' }],
    viewRange: [{ required: true }],
    file: [{ required: true }]
  }
})

const viewPersons = ref()
const isAdd = ref(true)
const { form, dialogParam, fileList, personList, rules } = toRefs(data)
watchEffect(() => {
  isAdd.value = !!location.href.match(/addTemplate/)
})

watch(
  fileList,
  (newValue, oldValue) => {
    form.value.fileNames = fileList.value.map(item => item.fileName)
  },
  { deep: true }
)
const props = defineProps({
  id: {
    type: String
  }
})

watch(
  () => props.id,
  (newValue, oldValue) => {
    if (newValue) {
      init()
    }
  }
)
init()
async function init() {
  if (!isAdd.value) {
    const id = props.id
    form.value.ctId = id
    try {
      // 获取表单内容，人员树
      const res = await contractdetails(id)
      if (res.code === 200 && res.data) {
        const response = res.data
        form.value.title = response.title
        form.value.type = response.type
        form.value.status = response.status
        form.value.viewPersons =
          response.viewPersons &&
          response.viewPersons.length &&
          response.viewPersons.map(item => item.key).join(',')
        form.value.defaultCheckedKeys =
          response.viewPersons &&
          response.viewPersons.length &&
          response.viewPersons.map(item => item.key)
        form.value.viewRange = response.viewRange
        form.value.telExplain = response.telExplain
        form.value.fileNames = response.sysAttachFiles.map(
          item => item.fileName
        )
        fileList.value = response.sysAttachFiles
        viewPersons.value =
          response.viewPersons &&
          response.viewPersons.length &&
          response.viewPersons.map(item => item.value).join(',')
      }
    } catch (error) {
      console.log(error)
    }
  }
  treeData()
}
// 设置人员树
async function treeData() {
  try {
    const res = await commonStore.getUseTreeData()
    personList.value = [res[0]]
  } catch (error) {
    console.log(error)
  }
}
/**
 * @param val 组件SelectDialog选中的值
 */
function selectFromValue(val) {
  form.value.viewPersons = val.defaultCheckedKeys.join(',')
  viewPersons.value = val.labelData.join(',')
  dialogParam.value.isDialog = false
  form.value.defaultCheckedKeys = val.defaultCheckedKeys
}

// 配置 SelectDialog组件所需参数
function changePerson() {
  dialogParam.value = {
    type: 'viewPersons',
    isDialog: true,
    data: personList.value,
    _data: [],
    multiple: true,
    defaultCheckedKeys: form.value.viewPersons ? [form.value.viewPersons] : [],
    checkStrictly: false,
    title: '指定人选择',
    searchConpany: false,
    switchRoles: ['组织架构', '角色列表']
  }
  if (form.value.defaultCheckedKeys && form.value.defaultCheckedKeys.length) {
    dialogParam.value.defaultCheckedKeys = form.value.defaultCheckedKeys
  }
}
function handleChange() {}
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

async function uploadEvent(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      form.value.fileNames.push(res.data.fileName)
      fileList.value.push(res.data)
    }
  } catch (error) {
    console.log(error)
    // proxy.$modal.msgError(error)
  }
}

function release() {
  console.log('release')
}
function agree() {
  console.info('agree')
}
function modification() {
  console.info('modification')
}
function Rejection() {
  console.info('Rejection')
}
function process() {
  console.info('process')
}
function save(e) {
  e.preventDefault()
  if (!form.value.title) {
    proxy.$modal.msgWarning('请输入合同模板标题')
    return
  }
  if (!form.value.status) {
    proxy.$modal.msgWarning('请选择合同模板类别')
    return
  }
  if (!form.value.fileNames.length) {
    proxy.$modal.msgWarning('请上传合同模板')
    return
  }
  if (fileList.value.length) {
    form.value.fileNames = fileList.value.map(item => item.fileName)
  }
  // proxy.$refs['templateFrom'].validate(async vaild => {
  // if (vaild) {
  if (isAdd.value) {
    contractSave(form.value).then(res => {
      proxy.$modal.msgSuccess('添加成功')
      router.push({
        path: '/sales/contract/contractTemplate'
      })
      useTagsViewStore().delView(router.currentRoute.value)
    })
  } else {
    contractUpdate(form.value).then(res => {
      proxy.$modal.msgSuccess('修改成功')
      router.push({
        path: '/sales/contract/contractTemplate'
      })
      useTagsViewStore().delView(router.currentRoute.value)
    })
  }
  // }
  // })
}
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
    // proxy.$modal.msgError(error)
  }
}

function closeDialog() {
  dialogParam.value.isDialog = false
}
</script>

<style lang="scss" scoped>
.templatePage {
  #temForm {
    .tip {
      @apply mr-3px;
      color: red;
    }
    .label {
      @apply text-right inline-block mr-10px;
      font-size: 14px;
      width: 180px;
    }
    // :deep .el-row {
    //   @apply my-20px;
    // }
    :deep .el-col {
      @apply flex;
    }
    :deep .el-textarea {
      width: 60%;
    }
    :deep .el-select {
      width: 60% !important;
    }
  }
}
</style>
